﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BestPrice.Library
{
    using Common;
    using System.Text.RegularExpressions;
    public class HtmlUtil
    {
        public static List<Product> ParseProduct(String htmlContent, WebSite webSite)
        {
            String Src = null;
            Formatter formatter = webSite.Formatter;
            var products = new List<Product>();
            Regex WebsiteRegex = new Regex(formatter.WebSitePattern);
            MatchCollection matchs = WebsiteRegex.Matches(htmlContent);
            int id = 1;
            foreach (Match math in matchs)
            {
                Src = math.ToString();

                String ImageUrl = GetContent(Src, formatter.BeginImage, formatter.EndImage);
                if (!ImageUrl.Contains("http"))
                    ImageUrl = webSite.BaseUrl + ImageUrl;

                String Title = GetContent(Src, formatter.BeginTitle, formatter.EndTitle);
                Regex regex = new Regex("\\(.*?\\)");
                Title =  regex.Replace(Title, "");

                String Detail = GetContent(Src, formatter.BeginDetail, formatter.EndDetail);

                String Price = GetContent(Src, formatter.BeginPrice, formatter.EndPrice);
                
                if (String.IsNullOrWhiteSpace(Price))  
                {
                    Price = "Not available!!";
                }
                
                String BaseURL = webSite.BaseUrl + GetContent(Src, formatter.BeginBaseURL, formatter.EndBaseURL);

                Product product = new Product(id++, Title, Detail, Price, ImageUrl, BaseURL);
                
                products.Add(product);

                if (id == 8)
                    break;
            }
            return products;
        }

        private static string GetContent(String Src, String BeginParttern, String EndParttern)
        {
            Regex BeginRegex = new Regex(BeginParttern);
            Regex EndRegex = new Regex(EndParttern);
            return EndRegex.Replace(BeginRegex.Match(Src).ToString(), "");

        } 
    }
}
